package com.dongdong.service.impl;

import com.dongdong.api.OrderItemAPI;
import com.dongdong.mapper.TbOrderItemMapper;
import com.dongdong.model.TbOrderItem;
import com.dongdong.model.TbOrderItemExample;
import com.dongdong.service.OrderItemService;
import com.dongdong.util.IdWorker;
import com.dongdong.vo.OrderItemVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class OrderItemServiceImpl implements OrderItemService {

    @Autowired
    private TbOrderItemMapper orderItemMapper;

    @Autowired
    private OrderItemAPI orderItemAPI;

    @Override
    public int orderItemGetOrderNoByOutRequestNo(String trade_no) {//退款 订单编号
        TbOrderItemExample example = new TbOrderItemExample();
        example.createCriteria().andOrderNoEqualTo(trade_no);
        List<TbOrderItem> tbOrderItems = orderItemMapper.selectByExample(example);

        for (TbOrderItem tbOrderItem : tbOrderItems) {
            IdWorker idWorker = new IdWorker();
            long l = idWorker.nextId();
            tbOrderItem.setStatus(3);
            tbOrderItem.setOutRequestNo(String.valueOf(l));
            int i = orderItemMapper.updateByPrimaryKeySelective(tbOrderItem);
            return i;
        }
        return 0;
    }


    @Override
    @Transactional
    public int orderItemAdd(String out_trade_no, String trade_no) {//付款成功  修改订单状态   增加流水号
        TbOrderItemExample example = new TbOrderItemExample();
        example.createCriteria().andOrderNoEqualTo(out_trade_no);
        List<TbOrderItem> tbOrderItems = orderItemMapper.selectByExample(example);

        for (TbOrderItem tbOrderItem : tbOrderItems) {
            if (Objects.equals(out_trade_no, tbOrderItem.getOrderNo())) {
                tbOrderItem.setOutTradeNo(trade_no);
                tbOrderItem.setStatus(1);
                int i = orderItemMapper.updateByPrimaryKeySelective(tbOrderItem);

                //先查询出  订单编号一致的数据  然后 修改order的状态 1 为已付款
                int i1 = orderItemAPI.getOrderNoUpSatus(tbOrderItem.getOrderNo());
                if (i > 0 && i1 > 0) {
                    return i1;
                }
            }
        }
        return 0;
    }

    @Override
    public List<OrderItemVO> getOrderIdByOrderItemOrderId(Long orderId) {
        TbOrderItemExample example = new TbOrderItemExample();
        example.createCriteria().andOrderIdEqualTo(orderId);

        List<TbOrderItem> tbOrderItems = orderItemMapper.selectByExample(example);

        List<OrderItemVO> collect = tbOrderItems.stream().map(orderitemlist -> {
            OrderItemVO vo = new OrderItemVO();
            BeanUtils.copyProperties(orderitemlist, vo);
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

}
